package com.jsmile.cloud.authc.web.security;

import java.util.Collection;
import java.util.List;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;

import com.jsmile.cloud.authc.api.exception.AuthcException;
import com.jsmile.cloud.authc.api.res.ResSysRoleResources;
import com.jsmile.cloud.authc.api.res.ResSysUser;
import com.jsmile.cloud.authc.sys.repo.SysRoleSearchRepository;
import com.jsmile.cloud.authc.sys.repo.SysUserSearchRepository;
import com.jsmile.mail.security.handler.JsmileContext;
import com.jsmile.mail.security.kit.WebKit;
import com.jsmile.mail.security.security.JsmileUser;
import com.jsmile.mall.api.enums.JSmileCodeEnum;
import com.jsmile.mall.api.enums.SfEnum;
import com.jsmile.mall.cache.kit.SpringKit;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class JsmileUserService implements UserDetailsService {

    @Override
    public UserDetails loadUserByUsername(String username) {
        SysUserSearchRepository userService = SpringKit.getBean(SysUserSearchRepository.class);
        SysRoleSearchRepository roleService = SpringKit.getBean(SysRoleSearchRepository.class);
        JsmileContext context = WebKit.getContext();
        ResSysUser userinfo = userService.findByUsername(username, context.getTenantId(), context.getUserType());
        // 账号不存在
        if (userinfo == null) {
            throw new AuthcException(JSmileCodeEnum.NOT_EXISTS_ACCOUNT);
        }
        // 帐号已被锁定
        if (SfEnum.S.getValue() == userinfo.getLocked()) {
            throw new AuthcException(JSmileCodeEnum.ACCOUNT_LOCKED);
        }
        ResSysRoleResources sysRoleResourcesVo = roleService.getRoleSources(userinfo.getId());
        sysRoleResourcesVo.setSysUser(userinfo);
        List<String> strpers = sysRoleResourcesVo.getStringPers();
        log.info("权限信息：{}", strpers);
        Collection<? extends GrantedAuthority> authorities = AuthorityUtils.createAuthorityList(strpers.toArray(new String[strpers.size()]));
        JsmileUser securityUser = new JsmileUser(userinfo, authorities);
        securityUser.setRoles(sysRoleResourcesVo.getRoles());
        securityUser.setPermissions(sysRoleResourcesVo.getPermissions());
        return securityUser;
    }
}
